<template>
  <setting-public-view
    current="cardManage"
    view-class="setting-view-main2"
    :nav="eventNav"
  >
    <!-- start 头部 -->
    <div class="event-additional-header">
      <div class="event-additional-header-tabs">
        <el-tabs v-model="activeTab">
          <el-tab-pane :label="$t('event.setting.additional.label1')" name="event-added">
            <div class="tab-desc">{{$t('event.setting.additional.des1')}}</div>
          </el-tab-pane>
          <el-tab-pane :label="$t('event.setting.additional.label2')" name="event-import">
            <div class="tab-desc">
              <i18n path="event.setting.additional.des2">
                <span place="data1">{{$t('common.base.preview')}}</span>
              </i18n>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div class="event-additional-header-btns" v-if="activeTab === 'event-added'">
        <el-button type="primary" @click="openAddEventAdditionalDialog(null)">
          <i class="iconfont icon-add2"></i>{{$t('common.base.create')}}
        </el-button>
      </div>
    </div>
    <!-- end 头部 -->

    <!-- start 已添加附加组件 -->
    <div class="event-additional-list" v-loading="loading" v-show="activeTab === 'event-added'">
      <draggable
        class="event-additional-list-draggable"
        v-bind="{ animation: 380, ghostClass: 'ghost' }"
        v-model="cardList"
        tag="div"
        @change="updateCardListOrder"
      >
        <card-item
          class="card-item"
          v-for="card in cardList"
          :key="card.id"
          :card="card"
          @update="initCardList"
          @edit="openAddEventAdditionalDialog"
          @statistics="openStatisticsDialog"
        ></card-item>
      </draggable>
    </div>
    <!-- end 已添加附加组件 -->

    <!-- start 从模版库添加 -->
    <div class="event-additional-template-list" v-show="activeTab === 'event-import'">
      <template-library :card-sys-list="cardSysList" @update="updateAdditionalList" />
    </div>
    <!-- end 从模版库添加 -->

    <!-- start 新建编辑附加组弹窗 -->
    <edit-cardname-dialog ref="batchCardnameDialog" @editCardSubmit="initCardList" />
    <!-- end 新建编辑附加组弹窗 -->

    <!-- start 统计 -->
    <statistical-dialog ref="statisteDialog" />
    <!-- end 统计 -->
  </setting-public-view>
</template>

<script>
/* constant */
import { ADDITIONAL_TYPE_MAP } from '../constant';
import { eventNav } from '../../components/settingPublicView/navList.js';
/* api */
import * as SettingServiceEventApi from '@src/api/SettingServiceEventApi';
/* components */
import draggable from 'vuedraggable';
import SettingPublicView from '../../components/settingPublicView';
import CardItem from './components/CardItem.vue';
import EditCardnameDialog from './components/EditCardnameDialog';
import statisticalDialog from './components/statisticalDialog';
import TemplateLibrary from './components/TemplateLibrary.vue';
/* util */
import { cloneDeep } from 'lodash';
/* service */
import IMService from '@service/IMService';

export default {
  name: 'service-event-additional',
  data() {
    return {
      loading: false,
      activeTab: 'event-added',
      cardList: [], //  已添加组件列表
      cardSysList: [], //  模板库列表
    };
  },
  computed: {
    imInitData() {
      return IMService.getIMInitData()
    },
    eventNav() {
      
      let newEventNav = cloneDeep(eventNav);
      
      // 未开启客户机器人
      if (!this.imInitData?.customerServiceRobot) {
        newEventNav.list = newEventNav.list.filter(nav => nav.type !== 'robotSetting')
      }
      
      // 未开启在线客服
      if (!IMService.getIMIsOpen()) {
        newEventNav.list = newEventNav.list.filter(nav => nav.type !== 'imSetting')
      }
      
      return newEventNav;
    }
  },
  methods: {
    /* 更新组件排序 */
    async updateCardListOrder() {
      try {
        const orderList = this.cardList.map((cardItem, idx) => ({
          id: cardItem.id,
          orderId: idx + 1,
        }));
      
        const res = await SettingServiceEventApi.updateCardOrderId(orderList);
        if (res.status != 0) return this.$message.error(res.message);
      } catch(err) {
        console.error('updateCardListOrder', err);
      }
    },
    /* 打开添加附加组件弹窗 */
    openAddEventAdditionalDialog(card) {
      this.$refs.batchCardnameDialog.openDialog(card);
    },
    /* 打开附加组件统计弹窗 */
    openStatisticsDialog(card) {
      this.$refs.statisteDialog.openDialog(card);
    },
    /* 初始化已添加的组件列表 */
    initCardList() {
      this.loading = true;
      SettingServiceEventApi.getEventCardList()
        .then(res => {
          const { status, message, data = [] } = res;

          if (status == 0) {
            this.cardList = data;
          } else {
            this.$message.error(message);
          }
        })
        .finally(() => {
          this.loading = false;
        })
        .catch(err => console.error(err))
    },
    /* 初始化模板库列表 */
    initTemplateLibraryList() {
      SettingServiceEventApi.getSystemTemplateList({ id: 1 })
        .then(res => {
          const { status, message, data = [] } = res;

          if (status == 0) {
            this.cardSysList = data.filter(card => card.cardName !== '工时记录')
              .map(item => {
                return {
                  ...item,
                  type: ADDITIONAL_TYPE_MAP[item.cardId],
                };
              });
          } else {
            this.$message.error(message);
          }
        })
        .catch(err => console.error(err))
    },
    /* 从模板库添加 */
    updateAdditionalList() {
      this.activeTab = 'event-added';
      this.initCardList();
    }
  },
  mounted() {
    this.initCardList();
    this.initTemplateLibraryList();
    
    // 修改标题
    if (window.frameElement) {
      const currentTabId = window.frameElement.dataset.id;
      let title = this.$t('event.setting.additional.title1')
      this.$platform.setTabTitle({
        id: currentTabId,
        title
      })
    }
  },
  components: {
    draggable,
    SettingPublicView,
    CardItem,
    EditCardnameDialog,
    statisticalDialog,
    TemplateLibrary,
  },
};
</script>

<style lang="scss" scoped>
.event-additional-header {
  width: 100%;
  margin-bottom: 12px;
  padding:16px;

  background: #fff;
  border-radius: $button-radius-base;
  display: flex;
  justify-content: space-between;

  &-tabs {
    ::v-deep  .el-tabs {
      &__header {
        margin: 0 0 0 -16px;

        .el-tabs__item {
          padding: 0 24px !important;
          color: $text-color-regular;
          font-weight: normal;

          &.is-active {
            color: $color-primary;
          }
        }
      }

      &__nav-wrap {
        &:after {
          height: 0;
        }
      }
    }

    .tab-desc {
      max-width: 680px;
      line-height: 20px;
      margin-top: 14px;
      color: $text-color-regular;
      font-size: $font-size-small;

      span {
        color: $text-color-primary;
      }
    }
  }

  &-btns {
    margin: 30px 0 0 16px;

    .el-button {
      padding: 8px 15px;
      .iconfont {
        margin-right: 8px;
      }
    }
  }
}

.event-additional-list-draggable{
  @include dynamic-card-list(2, 'card-item');
}

.event-additional-list,
.event-additional-template-list {
  height: calc(100% - 120px);
  overflow: auto;

  &-draggable {
    display: flex;
    flex-wrap: wrap;
    align-content: flex-start;

    .card-item {
      margin: 0 12px 12px 0;
    }
  }
}
</style>
